package com.sz.common.core.system.service.impl;

import com.sz.common.base.constants.AppDomain;
import com.sz.common.base.service.AbstractService;
import com.sz.common.core.system.entity.SysMail;
import com.sz.common.core.system.service.SysMailService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Function: SysMailServiceImpl <br>
 * Author: Charles <br>
 * Date: 2016-11-29 14:04:00
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class SysMailServiceImpl extends AbstractService implements SysMailService {

    /**
     * @param from    发送人邮件
     * @param to      接收人邮件列表
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    @Override
    public long createMail(String from, String[] to, String subject, String content) {
        long id = this.createMail(AppDomain.OPERATION, "system", from, to, null, subject, content, 1, null, null);
       return id;
    }

    /**
     * 新建邮件
     *
     * @param domainId      域Id
     * @param catalog       分类目录
     * @param from          发送人邮件
     * @param to            接收人邮件列表
     * @param cc            抄送人邮件列表
     * @param subject       邮件主题
     * @param content       邮件内容
     * @param priority      优先级
     * @param scheduledTime 定时发送时间
     */
    @Override
    public long createMail(int domainId, String catalog, String from, String[] to, String[] cc,
                           String subject, String content, int priority, Date scheduledTime , String templateName) {
        if (from == null || from.trim().length() == 0) {
            throw new IllegalArgumentException("'from' can not be empty");
        }
        if (to == null || to.length == 0) {
            throw new IllegalArgumentException("'to' can not be empty");
        }
        SysMail mail = new SysMail();
        mail.setDomainId(domainId);
        if (catalog != null && catalog.length() > 0) {
            mail.setCatalog(catalog);
        }
        mail.setSender(from);
        mail.setReceiver(StringUtils.join(to, ';'));
        if (cc != null && cc.length > 0) {
            mail.setCc(StringUtils.join(cc, ';'));
        }
        if (subject == null) {
            subject = "no subject";
        }
        mail.setSubject(subject);
        mail.setBody(content);
        mail.setPriority(priority);
        mail.setTemplate(templateName);
        if (scheduledTime == null) {
            scheduledTime = new Date();
        }
        mail.setScheduledTime(scheduledTime);

      dao.save(getSqlName("insertSelective"), mail);
      return mail.getId();
    }

    /**
     * 获取mail
     *
     * @param id mail Id
     * @return
     */
    @Override
    public SysMail getMailById(long id) {
        Object obj = this.dao.findForObject(getSqlName("selectByPrimaryKey"), id);
        return (SysMail) obj;
    }

    /**
     * 获取所有为发送的邮件Id列表
     *
     * @param domainId 域Id
     * @return
     */
    @Override
    public List<Long> getUnsentMails(int domainId) {
        List<Long> ids = this.dao.findForList(getSqlName("selectUnsentMailIds"),
                domainId, Long.class);
        return ids;
    }

    /**
     * @param mailId  mailId
     * @param success 是否发送成功
     * @param errorCode
     */
    @Override
    public void updateSentResult(long mailId, boolean success, String errorCode,String errorMsg) {
        SysMail mail = getMailById(mailId);
        if (mail != null) {
            if (success) {
                mail.setIsSent(true);
                mail.setSendTime(new Date());
            } else {
                mail.setSendTime(new Date());
                mail.setRetry(mail.getRetry() + 1);
                mail.setErrorCode(errorCode);
                mail.setErrorMsg(errorMsg);
            }
            this.dao.update(getSqlName("updateByPrimaryKeySelective"), mail);
        }
    }

    @Override
    public List<SysMail> getAllNeedSentMails() {
        List<SysMail> needSendMails = this.dao.findForList(getSqlName("selectNotSendMails"), null, SysMail.class);
        return needSendMails;
    }

    /**
     * @param from    发送人邮件
     * @param to      接收人邮件列表
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    @Override
    public long createMail(String from, String[] to, String subject, String content, String templateName) {
      return this.createMail(AppDomain.OPERATION, "system", from, to, null, subject, content, 1, null, templateName);
    }

    @Override
    public void setMailFailStatus(long mailId, String errorCode, String errorMsg) {
        SysMail mail = getMailById(mailId);
        if (mail != null) {
            mail.setRetry(10);
            mail.setSendTime(new Date());
            mail.setErrorCode(errorCode);
            mail.setErrorMsg(errorMsg);
            this.dao.update(getSqlName("updateByPrimaryKeySelective"), mail);
        }
    }

    @Override
    protected String getMapperNamespace() {
        return "com.sz.common.core.system.mapper.SysMailMapper";
    }
}
